const {
	http
} = require("../../../../utils/apiutils");
const util = require("../../../../utils/util")
const app = getApp()
const wxml2canvas = require('../../../../utils/wxml2canvas.js')

import {
	wescoket
} from '../../../../utils/scoket'
let connectSocket = null;
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		shareShow: false,
		CustomBar: 0,
		statusBar: 0,
		showcollapse: false,
		collapse: false,
		fpx: 0,
		steps: [{
				text: '2020.11.22',
				desc: '开始报名',
			},
			{
				text: '2020.11.22',
				desc: '截止报名',
			},
			{
				text: '2020.11.22',
				desc: '工作时间',
			},
			{
				text: '2020.11.22',
				desc: '工作结束',
			},
		],
		jobData: {},
		latitude: 23.095994,
		longitude: 113.325520,
		markers: [],
		isdescription: false,
		userInfo: {},
		btnType: 0, // 1  马上接单 2  立即接单
		animationData: {}, //  小程序动画对象
		connectSocket: {}, // 小程序scoket对象
		timer: null,
		timer1: null,
		jgtime: 5000, // 心跳间隔时间
		lockReconnect: false,
		is_first: false,
		closeScoket: false,


		isCanDraw: false,
		bgImg: 'https://linghuoimage.xbbzp.com/FkUVOU3IK6srYPkY_EJQ6-DVaRSD',
		code_img: 'https://linghuoimage.xbbzp.com/FkUVOU3IK6srYPkY_EJQ6-DVaRSD',
		obj: {
			width: '750px',
			height: '1334px',
			code_width: '200px',
			code_height: '200px',
			bottom: '185px',
			left: '275px',
			btn_background: '#8E050D',
			borderWidth: '10px',
			borderRadius: '50%',
		},
		imgs: [],
		shareTime: 0,
		startTime: 0,
		leaveTime: 0,
		hasShareHai: false, //默认为  false   点击海报分享为 true   分享岗位为false
		pageY: 0,
		hideBoxMb: '-940rpx',
		// hideBoxMb:'-400rpx',
		// hideBoxMb:'0rpx',
		scrollTimer: null,
		hidedom: null,
		screenH: 0,
		showbord: false,
		maxy: 520,
		scrollTop: 0,
		xs: [],
		spread: false,
		notice: true,
		movetimer: null,
		movestarttime: 0,
		showpage: false,
		percentage: 0,
		isBaomingObj:{},
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		let CustomBar = app.globalData.CustomBar;
		let statusBar = app.globalData.statusBar
		this.setData({
			CustomBar: CustomBar - statusBar,
			statusBar: statusBar,
		})
		if (options.code) {
			getApp().globalData.inviteCode = options.code;
		}
		var that = this;
		wx.getSystemInfo({
			success: (result) => {
				var spx = 280 / 750 * result.windowWidth;
				var fpx = 500 / 750 * result.windowWidth;
				that.setData({
					sh: result.windowHeight - CustomBar,
					shs: result.windowHeight - CustomBar - spx,
					fpx: fpx
				})
				console.log("-----宽度-----", fpx)
			},
		})
		let id = options.id;

		console.log("------工作的id----", id, )
		this.setData({
			id: id,
			showpage: getApp().globalData.showpage
		})

		// this.animation  = wx.createAnimation({
		//   duration: 500,
		//   timingFunction: 'linear',
		// })
		this.animation = wx.createAnimation({
			duration: 3000,
			timingFunction: 'linear',
			delay: 0,
		})
		// this.getCode()
		this.getJob()

	},
	callouttap: function () {
		wx.openLocation({
			latitude: Number(this.data.jobData.lat),
			longitude: Number(this.data.jobData.lng),
			name: this.data.jobData.workPlace,
			address: this.data.jobData.workPlace,
		})
	},
	//获取工作详情信息
	getJobData: function (id) {

		var that = this;
		wx.showLoading({
			title: '加载中...',
		})
		http.getJobData(id,
			function (res) {
				wx.hideLoading()
				console.log("------岗位详情---", res);
				if (res.code == 0) {
					let db = res.data;
					var data = {
						id: 4,
						latitude: db.lat,
						longitude: db.lng,
						width: 30,
						height: 30,
						iconPath: '../../resources/location.png',
						customCallout: {
							anchorY: 0,
							anchorX: 20,
							display: 'ALWAYS',
						},
					}
					res.data.image = res.data.image.split(',') || [];
					let percentage = parseInt(res.data.registrationNumber / res.data.number * 100)
					// res.data.type=2;
					that.setData({
						jobData: res.data,
						isdescription: true,
						markers: [data],
						notice: res.data.factory.notice ? true : false,
						hideBoxMb: res.data.factory.notice ? '-810rpx' : '-940rpx',
						percentage: percentage < 2 ? 2 : percentage
					})
					that.setCollapse()
				} else {
					wx.showToast({
						title: res.message,
						icon: "none",
					})
				}
			},
			function (err) {
				wx.hideLoading()
			})
	},

	markertap(e) {
		console.log('@@@ markertap', e)
	},

	oncliclCall: function (e) {

		wx.makePhoneCall({
			phoneNumber: this.data.jobData.contactPhone //仅为示例，并非真实的电话号码
		})

	},
	onclickBack: function (e) {
		let arr = getCurrentPages().length
		let _this = this;
		this.data.closeScoket = true
		// connectSocket.close();
		clearTimeout(_this.data.timer);
		clearTimeout(_this.data.timer1);
		if (arr > 1) {
			wx.navigateBack({
				delta: 1,
			})
		} else {
			wx.switchTab({
				url: '/pages/tabBar/home/index',
			})
		}
		getApp().globalData.inviteCode = "";
	},

	onclickjob_favorite: function (e) {
		if (this.data.jobData.favorite) {
			var that = this;
			wx.showLoading({
				title: '加载中...',
			})
			http.job_favoriteD(this.data.jobData.id,
				function (res) {
					wx.hideLoading()
					if (res.code == 0) {
						wx.showToast({
							title: "取消成功",
							icon: "none",
						})

						that.setData({
							"jobData.favorite": false,
						})
					} else {
						wx.showToast({
							title: res.message,
							icon: "none",
						})
					}
				},
				function (err) {
					wx.hideLoading()
				})


		} else {
			var that = this;
			wx.showLoading({
				title: '加载中...',
			})
			http.job_favorite(this.data.jobData.id,
				function (res) {
					wx.hideLoading()
					if (res.code == 0) {
						wx.showToast({
							title: "收藏成功",
							icon: "none",
						})
						that.setData({
							"jobData.favorite": true,
						})
					} else {
						wx.showToast({
							title: res.message,
							icon: "none",
						})
					}
				},
				function (err) {
					wx.hideLoading()
				})

		}



	},
	dingyue(event) {
		this.setData({
			btnType: event.currentTarget.dataset.key
		})
		getApp().globalData.dingyue(this.onclickNext)
	},
	onclickNext() {
		if(this.data.isBaomingObj.code!=0){
			wx.showToast({
			  title: this.data.isBaomingObj.message,
			  icon:"none"
			})
			return ;
		}
		getApp().globalData.workInfo = this.data.jobData;
		let type = this.data.btnType;

		if (!app.globalData.userInfo.idNumber) {
			// 当前职位是全职还是兼职
			getApp().globalData.isJorQ = type == 1 ? 1 : 2;
			wx.showModal({
				title: "提示",
				content: "您还没有实名认证无法报名，是否去实名认证",
				confirmText: "去认证",
				success: function (res) {
					if (res.confirm) {
						wx.navigateTo({
							url: '/pages/me/pages/realname/realname?fromRoute=work'
						})
					}
				}
			})
			return
		}
		// 判断当前工作是全职还是兼职
		if (type == 1) {
			// 兼职直接报名
			this.payYj()
			// this.baoming(false);
			return;
		} else {
			
			if (this.data.jobData.interviewDate) {
				wx.navigateTo({
					url: '/pages/home/pages/apply/apply',
				})
			} else {
				this.payYj();
				
			}
		}

	},
	baoming(cancelConflict) {
		wx.showLoading()
		let data = {
			inviteCode: getApp().globalData.inviteCode || "",
			lng: this.data.longitude, //经度信息
			lat: this.data.latitude, //维度信息
		}
		if (cancelConflict) {
			data.ancelConflict = true; // 岗位是否冲突
		}
		http.registration(this.data.jobData.id, data, (res => {
				wx.hideLoading()
				if (res.code == 0) {
					console.log(that)
					var type = 1;
					if (this.data.jobData.type == 2) {
						type = 2;
					}
					let that = this;
					// 这里判断是因为 通过分享进入页面的话   getCurrentPages 中只存有当前页面 所以回退2步报错
					if (getCurrentPages().length > 1) {
						wx.navigateBack({
							delta: 2,
							success: function () {
								wx.navigateTo({
									url: '/pages/me/pages/action/action?type=' + type,
								})
								try {
									http.sendMsg(`${that.data.jobData.factoryId}/${that.data.jobData.factoryJobId}/${getApp().globalData.userInfo.id}`, () => {}, () => {})
									getApp().globalData.inviteCode = "";
								} catch (error) {
									console.log(error)
								}
							}
						})
					} else {
						try {
							wx.switchTab({
								url: '/pages/tabBar/home/index',
								success: function () {
									http.sendMsg(`${that.data.jobData.factoryId}/${that.data.jobData.factoryJobId}/${getApp().globalData.userInfo.id}`, () => {}, () => {})
									wx.navigateTo({
										url: '/pages/me/pages/action/action?type=' + type,
									})
								}
							})
						} catch (error) {
							console.log(error)
						}
					}

				} else if (res.code == 3) {
					var that = this;
					wx.showModal({
						title: "提示",
						content: "当前报名岗位与已录用岗位工作时间冲突,是否取消原报名岗位继续报名",
						success: function (res) {
							if (res.confirm) {
								that.baoming(true)
							}
						}
					})
				} else {
					wx.showToast({
						title: res.message,
						icon: "none",
					})
				}
			}).bind(this),
			function (err) {
				wx.hideLoading()
			})
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {
		setTimeout(_ => {
			let _this = this;
			let query = wx.createSelectorQuery();
			let hidedom = null;
			let screenH = wx.getSystemInfoSync().windowHeight
			query.select('.hide-b').boundingClientRect(rect => {
				hidedom = rect
				_this.setData({
					hidedom,
					screenH
				})
			}).exec();
		}, 1000)

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		this.getJobData(this.data.id)
		this.setData({
			userInfo: getApp().globalData.userInfo,
			is_first: false,

		})
		let _this = this;
		if (new Date().getTime() - this.data.shareTime > 3000 && this.data.shareTime && !this.data.hasShareHai) {
			wx.showModal({
				showCancel: false,
				title: '分享',
				content: '分享成功，好友认证后，福利自动到账',
				success(res) {
					_this.data.shareTime = 0;
					_this.data.hasShareBtn = false;
				}
			})
		}
		// this.webscoket()
		this.data.startTime = new Date().getTime();
		this.isBaoming();
	},
	//判断全文收起是否展示
	setCollapse: function () {
		var query = wx.createSelectorQuery();
		var that = this;
		query.selectAll('#co').boundingClientRect(function (rect) {
			rect.forEach((v, i) => {
				if (v.height > 60) { //判断高度,根据各种高度取折中
					that.setData({
						collapse: true,
						showcollapse: true
					})
				}
			})
		}).exec();
	},
	//点击全文收起
	changeCollapse: function () {
		this.setData({
			collapse: !this.data.collapse
		})
	},
	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {
		let _this = this;
		this.data.closeScoket = true;
		// connectSocket.close();
		clearTimeout(_this.data.timer);
		clearTimeout(_this.data.timer1);
		this.jobview()
	},
	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {
		let _this = this;
		this.data.closeScoket = true;
		// connectSocket.close();
		clearTimeout(_this.data.timer);
		clearTimeout(_this.data.timer1);
		this.jobview()
	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},


	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {
		var that = this;
		// 设置菜单中的转发按钮触发转发事件时的转发内容
		let shareurl = this.data.jobData.shareUrl;
		var code = ""
		if (shareurl) {
			code = util.GetQueryString(shareurl).code
		}
		var shareObj = {
			title: this.data.jobData.name + ' ' + this.data.jobData.salary / 100 + '元/' + this.data.jobData.payType, // 默认是小程序的名称(可以写slogan等)
			path: '/pages/index/index?type=work&id=' + this.data.jobData.id + "&code=" + code, // 默认是当前页面，必须是以‘/'开头的完整路径
			imageUrl: '', //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
		}
		this.data.shareTime = new Date().getTime();
		return shareObj;

	},
	pulse: function () {
		this.animation.rotate(180).step()
		this.setData({
			animationData: this.animation.export()
		})
		let _this = this;
		let timer = setTimeout(() => {
			console.log('返回原样')
			_this.animation.scale(1, 1).step();
			_this.setData({
				animationData: _this.animation.export()
			});
			clearTimeout(timer);
			timer = undefined;
		}, 500)
	},
	webscoket() {
		let _this = this;
		if (!getApp().globalData.userInfo.id) return;
		console.log(this.data.id + ',' + getApp().globalData.userInfo.id)
		connectSocket = wx.connectSocket({
			url: 'wss://xbbws.xbbzp.com/linghuo/push/' + this.data.id + ',' + getApp().globalData.userInfo.id,
			header: {
				'content-type': 'application/json'
			},
			success() {
				console.log('创建链接');
				// _this.observerTimer()
			},
			fail() {
				// _this.observerTimer();
			}
		})
		connectSocket.onOpen(function () {
			console.log('打开链接')
		})
		connectSocket.onMessage(res => {
			console.log('接收数据onMessage1');
			// 分析数据 重置定时器
			this.observerTimer()
			// _this.pulse()
			if (res.data.indexOf('hired') > 0) {
				let data = JSON.parse(res.data);
				console.log(data)
				_this.setData({
					['jobData.hireNumber']: data.hired
				})
				wx.nextTick(() => {
					_this.pulse();
				})
			}
		});
		connectSocket.onError(res => {
			// 报错 重连

			console.log('报错')
			connectSocket.close();
			if (this.data.closeScoket) return;
			this.reconnect();
		});
	},
	observerClose() {
		connectSocket.onClose(res => {
			console.log('链接断开，需重新链接');
		})
	},
	observerSend(str) {
		console.log('发送数据', str)
		let _this = this;
		connectSocket.send({
			data: str,
			fail() {
				_this.webscoket()
			}
		})
	},
	reconnect() {
		if (this.data.lockReconnect) return;
		this.data.lockReconnect = true;
		let _this = this;
		setTimeout(function () { //没连接上会一直重连，设置延迟避免请求过多
			_this.webscoket()
			_this.data.lockReconnect = false;
		}, 5000);
	},
	observerClose() {
		connectSocket.onClose(res => {
			// 报错需重新链接
			this.webscoket();
		})
	},
	observerTimer() {
		clearTimeout(this.data.timer);
		clearTimeout(this.data.timer1);
		this.data.timer = null;
		this.data.timer1 = null;
		let _this = this;
		this.data.timer = setTimeout(() => {
			this.observerSend('timer send');
			this.data.timer1 = setTimeout(() => {
				console.log("后台挂掉，没有心跳了....");
				_this.observerClose();
			}, _this.data.jgtime)
		}, this.data.jgtime)
	},
	createShareImage() {
		this.setData({
			isCanDraw: true
		})
	},
	drawCanvas: function () {
		const wrapperId = '#work'
		const drawClassName = '.draw'
		const canvasId = 'canvas1'
		wxml2canvas(wrapperId, drawClassName, canvasId).then((res) => {
			console.log(res)
			// canvas has been drawn
			// can save the image with wx.canvasToTempFilePath and wx.saveImageToPhotosAlbum 
		}, rej => {
			console.log(rej)
		})
	},
	showview(e) {
		let imgSrc = e.currentTarget.dataset.img;
		wx.previewImage({
			urls: [imgSrc],
			current: imgSrc
		})
	},
	jobview() {
		let params = {
			viewStartTime: this.data.startTime,
			viewLeaveTime: new Date().getTime(),
			jobId: this.data.jobData.id
		}
		http.jobview(params, res => {}, err => {})
	},
	getCode() {
		let params = {
			path: 'pages/index/index?route=work&id=' + this.data.id + '&code=' + getApp().globalData.userInfo.inviteCode,
		}
		http.createQrcode4Job(params, res => {
			console.log(res)
		}, err => {})
	},
	showshare() {
		this.setData({
			shareShow: !this.data.shareShow
		})
	},
	toGwHai() {
		this.setData({
			hasShareHai: true
		})
		wx.navigateTo({
			url: '../zs/index?id=' + this.data.jobData.id + '&factoryJobId=' + this.data.jobData.factoryJobId
		})

	},
	aaa(e) {
		// console.log('start',e.changedTouches[0].pageY)
		this.setData({
			pageY: e.changedTouches[0].pageY
		})
	},
	ccc(e) {
		let hideBoxMb = this.data.screenH - this.data.hidedom.height - e.changedTouches[0].pageY;
		if (e.changedTouches[0].pageY > this.data.screenH / 5) {
			hideBoxMb = this.data.notice ? '-810rpx' : '-940rpx'
		}
		if (e.changedTouches[0].pageY < this.data.screenH / 4 * 3) {
			hideBoxMb = 0 + 'rpx'
		}
		this.setData({
			hideBoxMb: hideBoxMb,
		})
	},
	bbb(e) {
		let _this = this;
		let hideBoxMb = this.data.screenH - this.data.hidedom.height - e.changedTouches[0].pageY;
		if (this.data.screenH - e.changedTouches[0].pageY > this.data.hidedom.height) {
			hideBoxMb = '0px'
		} else {
			hideBoxMb = hideBoxMb + 'px'
		}
		// if (hideBoxMb<-510) { 
		//   hideBoxMb = '-925rpx'
		// }
		_this.setData({
			hideBoxMb: hideBoxMb
		})
	},
	canceltouch(e) {},
	funcClick(e) {
		let key = e.currentTarget.dataset.key * 1;
		let _this = this;
		switch (key) {
			case 1:
				// _this.setData({
				// 	showbord: true
				// })
				// setTimeout(_ => {
				// 	_this.setData({
				// 		showbord: false
				// 	})
				// }, 2000)
				break;
			case 3:
				wx.navigateTo({
					url: '/pages/clock/pages/jobvideo/index?id=' + this.data.jobData.id
				})
				break;
			case 4:
				wx.navigateTo({
					url: '/pages/clock/pages/jobimg/index?id=' + this.data.jobData.id
				})
				break;
			case 5:
				this.showshare()
				break;
		}
	},
	fzgn(e) {
		let key = e.currentTarget.dataset.key * 1;
		let _this = this;
		switch (key) {
			case 1:
				wx.navigateTo({
					url: '/pages/clock/pages/jobflow/index?id=' + this.data.id + '&type=' + key,
				})
				break;
			case 2:
				wx.navigateTo({
					url: '/pages/clock/pages/jobflow/index?id=' + this.data.id + '&type=' + key,
				})
				break;
		}
	},
	viewmove(e) {
		if (e.detail.y < this.data.screenH - this.data.hidedom.height) {
			this.setData({
				maxy: this.data.screenH - this.data.hidedom.height
			})
		}
		if (e.detail.y > 520) {
			this.setData({
				maxy: 520,
				scrollTop: 1
			})
		}
	},
	ddd(e) {
		if (e.changedTouches[0].pageY > 0 && e.changedTouches[0].pageY < this.data.screenH / 2) {
			this.setData({
				maxy: this.data.screenH - this.data.hidedom.height
			})
		}
		if (e.changedTouches[0].pageY > this.data.screenH / 2) {
			this.setData({
				maxy: 520,
				scrollTop: 2
			})
		}
	},
	getJob() {
		var data = {
			"pageNo": 1, //手机号码
			"pageSize": "4", //密码
			lat: getApp().globalData.lat,
			type: 2,
			lng: getApp().globalData.lng
		}
		console.log(this.data)
		var that = this;
		wx.showLoading({
			title: '加载中...',
		})
		http.getJob(data,
			function (res) {
				wx.hideLoading()
				console.log("------用户登录信息哦---", res);
				if (res.code == 0) {
					that.setData({
						xs: res.data.records
					})
				} else {
					wx.showToast({
						title: res.message,
						icon: "none",
					})
				}
			},
			function (err) {
				wx.hideLoading()
			})
	},
	toJob(e) {
		let id = e.currentTarget.dataset.id;
		wx.redirectTo({
			url: '/pages/home/pages/work/work?id=' + id,
		})
	},
	spread() {
		let bottom = 0;
		if (parseInt(this.data.hideBoxMb) > -50) {
			bottom = this.data.notice ? '-810rpx' : '-940rpx'
		} else {
			bottom = '0rpx'
		}
		this.setData({
			spread: true
		})
		wx.nextTick(_ => {
			this.setData({
				hideBoxMb: bottom
			})
		})
		setTimeout(_ => {
			this.setData({
				spread: false
			})
		}, 1000)

	},
	payYj() {
		http.payMargin({
				jobId: this.data.id
			}, function (res) {
				console.log("支付",res)
				return
				this.baoming(false);
			},
			function (err) {
				wx.hideLoading()
			})
	},
	isBaoming(){
		let data = {
			inviteCode: getApp().globalData.inviteCode || "",
			lng: this.data.longitude, //经度信息
			lat: this.data.latitude, //维度信息
			jobId:this.data.id
		}
		http.checkRegistration(data,res=>{
			this.setData({
				isBaomingObj:res
			})
		},err=>{})
	}
})